package mall.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import mall.bean.Product;
import mall.dao.ProductDao;

public class ProductDaoImpl implements ProductDao {
	@Override
	public void save(Product obj)  {
		// 先进行数据预处理
		obj.setCreateTime(new java.util.Date());
		obj.setLastModifiedTime(obj.getCreateTime());

		String sql = "INSERT INTO `product` " + "(`cid`, `title`, `sell_point`, `price`, `cover`, "
				+ "`stock`, `description`, `create_time`, " + "`last_modified_time`, `on_sale`, `on_sale_time`) "
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		JdbcTemplate.update(sql, obj.getCid(), obj.getTitle(), obj.getSellPoint(), obj.getPrice(), obj.getCover(),
				obj.getStock(), obj.getDescription(), obj.getCreateTime(), obj.getLastModifiedTime(), obj.isOnSale(),
				obj.getOnSaleTime());

	}

	@Override
	public void delete(Long id)  {
		String sql = "DELETE FROM product WHERE pid = ?";
		JdbcTemplate.update(sql, id);
	}

	@Override
	public void update(Product obj)  {
		String sql = "UPDATE `product` SET `cid`=?, `title`=?, `sell_point`=?, `price`=?,`cover`=?, `stock`=?, `description`=?, `create_time`=?, `last_modified_time`=?, `on_sale`=?, `on_sale_time`=? WHERE (`pid`=?)";
		JdbcTemplate.update(sql, obj.getCid(), obj.getTitle(), obj.getSellPoint(), obj.getPrice(), obj.getCover(),
				obj.getStock(), obj.getDescription(), obj.getCreateTime(), obj.getLastModifiedTime(), obj.isOnSale(),
				obj.getOnSaleTime(), obj.getPid());
	}

	@Override
	public Product findById(Long id)  {
		String sql = "SELECT pid, cid, title, sell_point as sellPoint, price, cover, stock, description, create_time as createTime, last_modified_time as lastModifiedTime, on_sale as onSale, on_sale_time as onSaleTime FROM product WHERE pid = ?";
		return JdbcTemplate.query(new BeanHandler<Product>(Product.class), sql, id);
	}

	@Override
	public long count()  {
		String sql = "SELECT COUNT(pid) FROM product";
		return JdbcTemplate.query(new ScalarHandler<Long>(), sql);
	}

	@Override
	public List<Product> findListPage(int skip, int take)  {
		String sql = "SELECT * FROM product ORDER BY pid DESC LIMIT ?, ?";
		return JdbcTemplate.query(new BeanListHandler<Product>(Product.class), sql, skip, take);
	}

}
